package org.ring.common.transport;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @since 2024-07-21 17:27
 */
public class ConnectionManager {

    private final boolean client;
    private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    final ConcurrentMap<Object, Connection> connections = new ConcurrentHashMap<>();
    final CopyOnWriteArrayList<ConnectionListener> listeners = new CopyOnWriteArrayList<>();

    public ConnectionManager() {
        this(true);
    }

    public ConnectionManager(boolean isClientSide) {
        this.client = isClientSide;
    }


    public void addConnectionListener(ConnectionListener connectionListener){
        listeners.add(connectionListener);
    }

    public Connection addConnection(Connection newConn) {
        Connection oldConn = connections.putIfAbsent(newConn.connectionId(), newConn);
        return oldConn == null ? newConn : oldConn;
    }


    public Connection remove(Connection c) {
        if(logger.isDebugEnabled()){
            logger.debug("The connection of {} was removed! {}", c.connectionId(), c);
        }
        for(ConnectionListener connectionListener : listeners){
            connectionListener.onDisConnected(c);
        }
        return connections.remove(c.connectionId());
    }

}
